import $service from '../../../../service.js';
var that;
let doctorId;
let log_type;
let doctorName;
const app = getApp();
Page({
  data: {
    primaryHospital: '', // 初诊医院名称
    primaryTime: '', // 初诊时间
    hisType: $service.isHis,
    id: '',
    age: 0,
    patientName: '',
    healthCardNo: '',
    isagreen: false,
    patientList: [],
    oosParams: {},
    toView: '',
    medicalRecordImage:[], //病历图片数据
    paymentmethod:1, //付费类型
    tipIndex: 0,
    tipKey: [2, 6, 9],
    tipList: [],
    isShow: false
  },
  onLoad(e) {
    doctorId = e.doctorId;
    log_type = e.log_type;
    doctorName = e.doctorName
    this.getAgreement()
    this.setData({
      'patientInfoData.doctorId': Number(e.doctorId),
      'patientInfoData.inquiryType': e.log_type
    })
    this.socketInit()
    this.ossPolicy()
  },
  onShow() {
    that = this.data;
    this.getInquiryPatientInfoList()
  },
  socketInit() {
    app.webSocket.initWebSocket({ url: $service.wsUrl})
  },
  ossPolicy() {
    app.http.ossPolicy().then(res => {
        this.setData({
            oosParams: res.data
        })
    })
},
  //立即咨询
  goInquiry() {
    let that = this.data
    if (!that.id) {
      $service.showToast('请选择就诊人');
      return;
    }
    if (!that.primaryHospital) {
      $service.showToast('请输入初诊医院名称');
      return
    }
    if (!that.primaryTime) {
      $service.showToast('请选择初诊时间');
      return
    }
    if (that.medicalRecordImage.length < 1) {
      $service.showToast('请上传至少一张初诊相关资料图片');
      return
    }
    if (that.isagreen == false) {
      $service.showToast('请查阅《联网医院服务协议》以及《互联网医院服务知情同意协议书》并勾选我已详细阅读');
      return;
    }
    if (this.data.age <= 14 && $service.isEsgin) {
      $service.showToast('暂不支持对14岁及14岁以下的患者进行问诊')
      return
    }
    if (!that.healthCardNo && that.hisType) {
      wx.showModal({
        title: '温馨提示',
        content: '确认就诊人信息无误？',
        confirmText: '确认无误',
        cancelText: '查看信息',
        confirmColor: '#1189FF',
        success: (res) => {
          if (res.confirm) {
            this.addInquiryPatientInfo()
          } else if (res.cancel) {
            $service.openPage(`./../inquiry_person/inquiry_person?id=${that.id}`)
          }
        }
      })
      return
    }
    this.addInquiryPatientInfo()
  },
  addInquiryPatientInfo() {
    let that = this.data
    wx.showLoading({
      title: "问诊保存中",
      mask: true
    });
    let params = {
      doctorId: doctorId,
      inquiryPatientId: this.data.id,
      inquiryType: log_type,
      medicalRecord: that.medicalRecordImage.join(),
      paymentmethod:this.data.paymentmethod,
      primaryHospital: that.primaryHospital,
      primaryTime: that.primaryTime
    }
    app.http.addInquiryPatientInfo(params).then(res => {
      let {logId, doctorImId, userIm, inquiryPatientId} = res.data
      app.webSocket.sendWebSocketMsg({
        data: {
          "logId": logId,
          "packageMsg": "",
          "packageType": 5,
          "doctorImId": doctorImId

        },
      })
      if (log_type == 1 || log_type == 2) {
        app.http.frozenOrder({logId: res.data.logId}).then(() => {
          $service.removeStore('tencentConfigP') // 清除上一次的视频数据缓存
          wx.reLaunch({
            url: '../../../chat/user_chat/Waiting/waitingChat?doctorId=' + doctorId + '&doctorImId=' + doctorImId + '&logId=' + logId + '&log_type=' + log_type
          })
        }).catch(err => {
          $service.showToast(err.msg)
        })
      } else {
        let params = {
          packageType: 3,
          msgType: "6",
          friendId: userIm,
          inquiryLogId: logId,
          msgUserName: doctorName,
          msgDate:  $service.getDate()
        }
        params.msgText = '请描述您的症状【感受最明显的一个或者数个症状或(体征)】和患病时长【起病至就诊的时间】'
        app.webSocket.sendWebSocketMsg({data: params})
        setTimeout(()=>{
          params.msgText = '若已回答完毕记得点击下方【已完成】。'
          app.webSocket.sendWebSocketMsg({data: params})
        },800)
        setTimeout(() => {
          wx.redirectTo({
            url: `/pages/chat/user_chat/user_chat?logId=${logId}&imId=${doctorImId}&inquiryPatientId=${inquiryPatientId}&log_type=${log_type}&doctorId=${doctorId}&doctorName=${doctorName}&myIM=${userIm}`
          })
        },1000)
      }
    }).catch(err => {
      if (err.msg == '用户已在问诊中') {
        wx.showModal({
          title: '提示',
          showCancel: false,
          content: '你有一个问诊尚未结束，请先结束',
          success: (res) => {
            if (res.confirm) {
              this.userEndInquiry()
            } 
          }
        })
        return
      }
      $service.showToast(err.msg);
    }).finally(res => {
        // wx.hideLoading();
    })
  },
  // 结束问诊中问诊
  userEndInquiry() {
    app.http.userEndInquiry({
      "doctorId": doctorId,
      "userId": JSON.parse(wx.getStorageSync('userInfo')).id
    }).then(res => {
      $service.showToast(res.msg)
    }).catch(err => {
      $service.showToast(err.msg)
    })
  },
  //协议选择框
  choosetap() {
    if (!this.data.isagreen) {
      this.data.isShow = true
    } else {
      this.data.isagreen = false
    }
    this.setData({
      isShow: this.data.isShow,
      isagreen: this.data.isagreen 
    })
  },
  // 前往协议页
  gotopage(e) {
    let {type} = e.currentTarget.dataset
    this.setData({
      isShow: true
    })
  },
  // 添加或修改就诊人信息
  goPerson(e) {
    let {id} = e.currentTarget.dataset
    $service.openPage(`./../inquiry_person/inquiry_person?id=${id}`)
  },
  // 获取就诊人列表
  getInquiryPatientInfoList() {
    app.http.getInquiryPatientInfoList().then(res => {
      this.setData({
        patientList: res.data.list
      })
      if (this.data.patientName) {
        if (res.data.list.filter(item => {  if (item.id == this.data.id) {return item}}).length == 0) {
          this.setData({
            patientName: '',
            id: ''
          })
        }
      }
    }).catch(err => {
      $service.showToast(err.msg)
    })
  },
  // 选择就诊人
  choosePatient(e) {
    let {id, name, paymentmethod, healthCardNo, age} = e.currentTarget.dataset
    console.log(e.currentTarget.dataset)
    this.setData({
      toView: 'v' + id,
      id,
      age,
      patientName: name,
      paymentmethod,
      healthCardNo
    })
  },
  //上传病历图片
  uploadImage(){
    wx.chooseImage({
      count: 8,
      success:(res)=>{
        res.tempFilePaths.forEach(item => {
          this.upLoad(item)
        })
      }
    })
  },
  // 上传图片
  upLoad(imgPath) {
      let medicalRecordImage = this.data.medicalRecordImage;
      let oosParams = this.data.oosParams
      wx.uploadFile({
        url: oosParams.host,
        filePath: imgPath,
        name: 'file',
        formData: {
          name: $service.randomFilename(imgPath),
          key: oosParams.dir +  $service.randomFilename(imgPath),
          dir: oosParams.dir,
          policy: oosParams.policy,
          OSSAccessKeyId: oosParams.accessid,
          success_action_status: "200", //让服务端返回200,不然，默认会返回204
          callback: oosParams.callback,
          signature: oosParams.signature
        },
        success: (uploadFileRes) => {
          if (this.data.medicalRecordImage.length < 8) {
            let imgData = JSON.parse(uploadFileRes.data)
            if (imgData.code == 1) {
              medicalRecordImage.push(imgData.data.filename);
              this.setData({
                medicalRecordImage
              })
            }
          }
        },
        fail: (res => {
          $service.showToast('上传oss失败')
        })
      });
  },
  //删除病历图片
  delRecordImage(e){
    let index = e.currentTarget.dataset.index;
    let medicalRecordImage = this.data.medicalRecordImage;
    medicalRecordImage.splice(index,1);
    this.setData({
      medicalRecordImage
    })
  },
  //预览病历图片
  previewImage(){
    let urls = []
    this.data.medicalRecordImage.forEach(item => {
      urls.push(item.replace(/https/, 'http'))
    })
    wx.previewImage({
      urls:urls
    })
  },
  // 退款
  refundBox() {
    wx.showModal({
      title: '温馨提示',
      content: '是否确认退款？',
      confirmText: '确认',
      cancelText: '取消',
      confirmColor: '#1189FF',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: "退款请求中",
            mask: true
          });
          let params = {
            "doctorId": doctorId,
            "userId": JSON.parse($service.getStore('userInfo')).id,
            "isFrozen": 0
          }
          app.http.refund(params).then(res => {
            $service.showToast('退费成功');
            setTimeout(() => {
              wx.navigateBack()
            },2000)
          }).catch(err => {
            $service.showToast(err.msg);
          }).finally(res => {
            wx.hideLoading();
          })
        }
      }
    })
  },
  inputChange(e) {
    this.setData({
      primaryHospital: e.detail.value
    })
  },
  // 选择初诊时间
  bindDateChange(e) {
    console.log($service.timeFormat(e.detail.value))
    if ($service.timeFormat(e.detail.value) > Date.parse(new Date())) {
      $service.showToast('初诊时间不能晚于当天日期')
      return
    }
    this.setData({
      primaryTime: e.detail.value
    })
  },
  // 获取协议
  getAgreement() {
    try {
      this.data.tipKey.forEach(async (item) => {
        let res = await app.http.getAgreement({id: item})
        if (res.data) {
          this.data.tipList.push(res.data)
        }
        // let {initName, initKey} = res.data
        // item.title = initName
        // item.text = initKey
        this.setData({
          tipList: this.data.tipList
        })
      })
    } catch (err) {
      $service.showToast(err.msg)
    }
  },
  changeTipIndx(e) {
    let {type} = e.currentTarget.dataset
    if (type == 'pre') { // 上一页
      this.data.tipIndex --
    } else if (type == 'next'){ // 下一页
      this.data.tipIndex ++
    } else { // 完成
      this.data.tipIndex = 0
      this.data.isShow = false
      this.data.isagreen = true
    }
    this.setData({
      tipIndex: this.data.tipIndex,
      isShow: this.data.isShow,
      isagreen: this.data.isagreen
    })
  }
})